<?php
namespace Admin\Controller;
use Think\Controller;
header("Content-Type:text/html; charset=utf-8");
class ClassesController extends Controller {


    public function _initialize()
    {
        if(!check_login()){
            $this->error('登录状态异常,请重新登录','/Admin/Login/login');
        }
    }


    //产品列表
    public function index()
    {
        $page       =   I('get.page');
        if(empty($page))    $page   =   0;

        $dep_id    =   I('get.dep_id');
        $department   =   M('department')->select();
        $sql['c.dep_id']  =   $dep_id;
        if($dep_id){
            $sql['c.dep_id'] =   $dep_id;
        }else {
            $inId       =   getArrIds($department);
            $sql   = "c.dep_id in ({$inId}) ";
        }

        $pages  =   getPage('class c',$sql,$page,10,5,"ab_department as d ON d.id = c.dep_id");
        $num    =   $pages['page']*10;

        $lists  =   M('class c')
            ->join("ab_department as d ON d.id = c.dep_id","left")
            ->where($sql)->order('c.id desc')->limit($num,10)
            ->field("c.id,c.name,c.creator,c.add_time,d.name depName")
            ->select();
        foreach($lists as $key => $v){
            $num = M("users")->where(array("class_id"=>$v['id']))->count();

            $lists[$key]['num']   =   $num;
        }


        $department   =   M('department')->select();
        $this->assign("lists",$lists);
        $this->assign("pages",$pages);
        $this->assign("dep_id",$dep_id);
        $this->assign("department",$department);
        $this->display();
    }

    public function ClassesAdd()
    {
        $data['dep_id']    =   I('post.dep_id');
        $data['name']    =   I('post.name');
        $data['creator']    =   session('user');
        $data['add_time']   =   getTime();

        $res = M('class')->add($data);
        if($res) $this->redirect('Admin/Classes/index');
        else $this->error("添加失败");

    }

    //删除数据
    public function delData()
    {
        $id     =   I('get.id');
        $table  =   I('get.table');
        $info   =   M($table)->where("id in ($id)")->find();

        $insert = M("users")->where(array('class_id'=>$id))->select();

        if ($insert) {
            $res = 2;
        } else {
            $res    =   M($table)->where("id in ($id)")->delete();
            if($res !== false){
                if($info['pic']) unlink('.'.$info['pic']);
                if($info['mini_pic']) unlink('.'.$info['mini_pic']);
            }
        }
        echo $res;


    }


}